import './index.less'

import Collaboration from '@tiptap/extension-collaboration'
import CollaborationCursor from '@tiptap/extension-collaboration-cursor'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Placeholder from '@tiptap/extension-placeholder'
import Text from '@tiptap/extension-text'
import { EditorContent, useEditor } from '@tiptap/react'
import React, { useEffect } from 'react'
import * as Y from 'yjs'

const colors = [
  '#958DF1', '#F98181', '#FBBC88', '#FAF594', '#70CFF8',
  '#94FADB', '#B9F18D', '#FF8A80', '#FFB74D',
  '#FFF176', '#AED581', '#4DB6AC', '#81C784', '#64B5F6'
]

// 根据用户名生成确定性颜色
const getColorByName = (name) => {
  // Simple hash function to get a number from a string
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    // eslint-disable-next-line no-bitwise
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  const index = Math.abs(hash % colors.length);
  return colors[index];
}

// 从 localStorage 获取用户名，如果不存在则返回默认值
const getUserNameFromStorage = () => {
  return localStorage.getItem('username') || 'Anonymous';
}

// 创建协同光标扩展配置
export const createCollaborationCursor = (provider, user = null) => {
  const currentUser = user || {
    name: getUserNameFromStorage(),
    color: getColorByName(getUserNameFromStorage()),
  }

  return CollaborationCursor.configure({
    provider,
    user: currentUser,
  })
}

// 协同光标组件示例
 
function CollaborationCursorComponent({ provider, ydoc }) {
  const editor = useEditor({
    extensions: [
      Document,
      Paragraph,
      Text,
      Collaboration.configure({
        document: ydoc,
      }),
      createCollaborationCursor(provider, {
        name: getUserNameFromStorage(),
        color: getColorByName(getUserNameFromStorage()),
      }),
      Placeholder.configure({
        placeholder: '开始协同编辑...',
      }),
    ],
  })
  editor.commands.updateUser({
    name: getUserNameFromStorage(),
    color: getColorByName(getUserNameFromStorage()),
  })
  return <EditorContent editor={editor} />
}

export default CollaborationCursorComponent
export { getUserNameFromStorage, getColorByName }